package com.itheima.controller;

import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
public class ConsumerController {
    @Autowired
    RestTemplate restTemplate;
    //引入注册中心接口
    @Autowired
    DiscoveryClient client;


    @GetMapping("{id}")
    public User findById(@PathVariable("id") long id){
        //远程服务调用
       // return restTemplate.getForObject("http://localhost:9001/user/"+id,User.class);

        List<ServiceInstance> instances = client.getInstances("user-service");
        String url ="";
        if(instances!=null&&instances.size()>0){
            ServiceInstance serviceInstance = instances.get(0);
            //获取域名
            String host = serviceInstance.getHost();
            System.out.println("host==>"+host);
            //获得端口号
            int port = serviceInstance.getPort();
            System.out.println("port==>"+port);
            //拼接路径
            url="http://"+host+":"+port+"/user/"+id;
        }
        return restTemplate.getForObject(url,User.class);
    }
}
